package com.example.shw

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.ContactsContract
import android.support.v4.content.CursorLoader
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.TextView

class ContactsActivity : AppCompatActivity(){
    private val PICK_CONTACT = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_contacts)
        val bn = findViewById<Button>(R.id.bn)
        bn.setOnClickListener {
            Log.d("12345","click bn")
            requestPermissions(arrayOf(android.Manifest.permission.READ_CONTACTS), 0x123)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == 0x123){
            if (permissions.size > 0 && grantResults!![0] == PackageManager.PERMISSION_GRANTED)
            {
                val intent = Intent()
                intent.action = Intent.ACTION_PICK
                intent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
                startActivityForResult(intent, PICK_CONTACT)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_CONTACT)
        {
            val contactData = data!!.data
            val cursorLoader = CursorLoader(this,contactData,null,null,null,null)
            val cursor = cursorLoader.loadInBackground()
            if (cursor!!.moveToFirst()){
                val contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
                Log.d("123456","contact_id=$contactId")
                val name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME))
                var phoneNumber = "此联系人暂未输入电话号码"
                val phones = contentResolver.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    "contact_id=$contactId",
                    null, null)
                Log.d("123456", ""+phones.moveToNext())
                if (phones!!.moveToFirst())
                {
                    phoneNumber = phones.getString(
                        phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                    )
                }

                phones.close()
                val show = findViewById<TextView>(R.id.contactshow)
                show.text = name
                val phone = findViewById<TextView>(R.id.phone)
                phone.text = phoneNumber
            }
            cursor.close()
        }
    }
}